package com.springboot.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import com.springboot.model.po.*;
import com.springboot.service.*;

import util.VerifyUtil;

@RefreshScope // 监听动态刷新
@RestController
@RequestMapping("/orders")
public class OrdersController {
	@Autowired
	OrdersService ordersService;
	@Autowired
	DiscoveryClient discoveryClient;

	@Autowired
	RestTemplate restTemplate;

	@PostMapping
	public ResponseEntity createOrders(@RequestBody Orders orders, @RequestParam String token) throws Exception {
		// 返回订单ID
		// businessId , userId , orderTotal , daId,typeId(如果没有则传入0)
		String userId_target = VerifyUtil.verify(token);
		if (userId_target == null || !orders.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");// 401
		}
		int result = ordersService.createOrders(orders);
		if (result > 0) {
			return ResponseEntity.ok(result);
		} else {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		}
	}

	@GetMapping("/{orderId}")
	public ResponseEntity getOrdersById(@PathVariable Integer orderId, @RequestParam("token") String token)
			throws Exception {
		String userId_target = VerifyUtil.verify(token);
		Orders orders = ordersService.getOrdersById(orderId);
		if (!orders.getUserId().equals(userId_target) || userId_target == null) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
		}
		if (orders == null) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("The requested resource was not found");
		} else {
			return ResponseEntity.ok(orders);
		}
	}

	@GetMapping("/users/{userId}")
	public ResponseEntity listOrdersByUserId(@PathVariable String userId, @RequestParam String token) throws Exception {
		String userId_target = VerifyUtil.verify(token);
		if (userId_target == null || !userId.equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");// 401
		}
		List<Orders> list = ordersService.listOrdersByUserId(userId);
		if (list.size() == 0 || list == null) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("The requested resource was not found.");
		} else {
			return ResponseEntity.ok(list);
		}
	}

	// 添加功能：支付全过程（优惠券+积分+流水+转账）
	@PutMapping("/payment")
//	public int updateOrderState(@RequestParam("orderId") String orderId, @RequestParam("orderState") Integer orderState) throws Exception{
	public ResponseEntity updateOrderState(@RequestParam("orderId") Integer orderId, @RequestParam String token)
			throws Exception {
		// 订单编号，状态，使用的优惠券类型
		Integer orderState = 1;
		Orders orders = ordersService.getOrdersById(orderId);
		Integer typeId = orders.getTypeId();
		String userId_target = VerifyUtil.verify(token);
		if (userId_target == null || !orders.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");// 401
		}
		if (orderState == null || orderId == null) {
			// 拦截非法参数，mapper会报：Cannot invoke "java.lang.Integer.intValue()" because
			// "orderState" is null
			return ResponseEntity.status(HttpStatus.BAD_REQUEST)
					.body("The request is missing one or more required parameters");
		}
		BigDecimal amount = orders.getOrderTotal();
		String flag = "";
		if (typeId != 0) {
			// 使用优惠券
			// 更新用户的优惠券数量
			String userId = orders.getUserId();

			List<ServiceInstance> instanceList_userCoupon = discoveryClient.getInstances("userCoupon-server");
			ServiceInstance instance_uc = instanceList_userCoupon.get(0);

			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			Map<String, Object> requestBody = new HashMap<>();
			HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
			ResponseEntity result_uc = restTemplate
					.exchange(
							"https://" + instance_uc.getHost() + ":" + instance_uc.getPort() + "/userCoupons/" + userId
									+ "/" + typeId + "?" + "token=" + token,
							HttpMethod.PUT, requestEntity, String.class);
			// 使用优惠券需要更改订单金额
			if (!result_uc.getStatusCode().equals(HttpStatus.OK))
				flag = "error with use coupon ";
//			else {
//				List<ServiceInstance> instanceList_coupon = discoveryClient.getInstances("coupon-server");
//				ServiceInstance instance_c = instanceList_coupon.get(0);
//				//result_c包含coupon（类别）
//				Coupon result_c = restTemplate.getForObject("https://"+instance_c.getHost()+":"+instance_c.getPort()+"/coupons/"+typeId+"?"+"token="+token, Coupon.class);
//				if(result_c.getCouponImg().equals("NOT_FOUND")) {
//					return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("TypeID not exists!");
//				}
//				
//				amount = amount.subtract(result_c.getValues());
//			
//			}		
		}
		// 不使用优惠券就单独改变订单状态即可
		// serviceImpl里面进行参数检验
		int result = ordersService.updateOrderState(orderId, orderState, amount);
		// 使用amount来提示转账数目
		if (result == 1) {
			return ResponseEntity.ok(flag + "ok");
		} else {
			// throw new Exception("error!");
			// 回滚
			String userId = orders.getUserId();

			List<ServiceInstance> instanceList_userCoupon = discoveryClient.getInstances("userCoupon-server");
			ServiceInstance instance_uc = instanceList_userCoupon.get(0);
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);

			Map<String, Object> requestBody = new HashMap<>();
			HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
			ResponseEntity result_uc = restTemplate.exchange(
					"https://" + instance_uc.getHost() + ":" + instance_uc.getPort() + "/userCoupons/number?typeId="
							+ typeId + "&userId=" + userId + "&token=" + token,
					HttpMethod.GET, requestEntity, String.class);
			// 新建
			if (result_uc.getStatusCode().equals(HttpStatus.NOT_FOUND) || result_uc.getStatusCode().equals(HttpStatus.OK)) {
				UserCoupon userCoupon = new UserCoupon();
				userCoupon.setTypeId(typeId);
				userCoupon.setUserId(userId);
				HttpEntity<UserCoupon> requestEntity1 = new HttpEntity<>(userCoupon, headers);
				ResponseEntity result_uc1 = restTemplate.exchange("https://" + instance_uc.getHost() + ":"
						+ instance_uc.getPort() + "/userCoupons/?token=" + token, HttpMethod.PUT, requestEntity1,
						String.class);
				if (!result_uc1.getStatusCode().equals(HttpStatus.OK)) {
					return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
							.body("An internal error occurred111");
				}

			}

			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		}
	}

}
